package com.xopencode.netty.nio;

import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Nio模拟netty boss work工作模式
 *
 * @author chunbin.mo
 */
public class NioServer {
    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);

            Selector boss = Selector.open();
            serverSocketChannel.register(boss, SelectionKey.OP_ACCEPT, null);
            serverSocketChannel.bind(new InetSocketAddress(8080));
            Worker worker = new Worker("worker");
            while (true) {
                boss.select();
                System.out.println("触发连接请求...");
                Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isAcceptable()) {
                        System.out.println("开始连接...");
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        //SocketChannel socketChannel = (SocketChannel) key.channel();
                        socketChannel.configureBlocking(false);
                        worker.regist(socketChannel);
                    }
                }

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    static class Worker implements Runnable {
        private Selector selector;
        private Thread thread;
        private String name;
        private volatile boolean registFlag;

        private ConcurrentLinkedQueue<Runnable> concurrentLinkedQueue = new ConcurrentLinkedQueue();

        public Worker() {
        }

        public Worker(String name) {
            this.name = name;
        }

        private void regist(SocketChannel socketChannel) throws IOException {
            if (!registFlag) {
                // start之前还是boss线程执行
                selector = Selector.open();
                thread = new Thread(this, name);
                thread.start();
                registFlag = true;
            }
            concurrentLinkedQueue.add(() -> {
                try {
                    socketChannel.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    throw new RuntimeException(e);
                }
            });
            selector.wakeup(); // 对于select进行一次唤醒
        }

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                    selector.select();
                    for (int i = 0; i < concurrentLinkedQueue.size(); i++) {
                        Runnable registeRunnable = concurrentLinkedQueue.poll();
                        if (registeRunnable != null) {
                            registeRunnable.run();
                        }
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            try {
                                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                                SocketChannel channel = (SocketChannel) key.channel();
                                channel.configureBlocking(false);
                                int read = channel.read(byteBuffer);
                                if (read == -1) {
                                    key.cancel();
                                    channel.close();
                                    continue;
                                }
                                byteBuffer.flip();
                                String sendStr = Charset.defaultCharset().decode(byteBuffer).toString();
                                System.out.println(sendStr);
                            } catch (IOException e) {
                                key.cancel();
                                e.printStackTrace();
                            }
                        }
                    }

            }

        }
    }

}
